<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :disabled="archiveStatus" :placeholder="$t('申请标题')" show-word-limit maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关联用印')" prop="sealId">
            <el-select v-model="form.sealId" :disabled="archiveStatus" :placeholder="$t('关联用印')" @change="changeSeal">
              <el-option
                v-for="dict in sealListOption"
                :key="dict.id"
                :label="$t(dict.actTitle)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('归档人')" prop="archivingPersonnel">
            <UserSelect v-model="form.archivingPersonnel" :disabled="archiveStatus" :placeholder="$t('归档人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('用印类型一级')">
            <dict-select
              v-model="form.sealTypeOne"
              disabled
              dictionary="seal_usine_type"
              :placeholder="$t('用印类型一级')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('用印类型二级')">
            <el-select v-model="form.sealTypeTwo" disabled :placeholder="$t('用印类型二级')">
              <el-option
                v-for="dict in sealTypeTwoOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('保管人')" prop="custodian">
            <UserSelect v-model="form.custodian" :disabled="archiveStatus" :placeholder="$t('保管人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('存放地')" prop="storagePlace">
            <el-input v-model="form.storagePlace" :disabled="archiveStatus" :placeholder="$t('存放地')" show-word-limit maxlength="300" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('创建时间')" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              clearable
              style="width: 200px"
              type="date"
              :disabled="archiveStatus"
              value-format="yyyy-MM-dd"
              :placeholder="$t('创建时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计归档时间')" prop="estimatedArchivingTime">
            <el-date-picker
              v-model="form.estimatedArchivingTime"
              clearable
              style="width: 200px"
              type="date"
              :disabled="archiveStatus"
              value-format="yyyy-MM-dd"
              :placeholder="$t('预计归档时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否完成归档')" prop="archiveCompleted">
            <el-input v-model="form.archiveCompleted" disabled show-word-limit maxlength="25" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" :disabled="archiveStatus" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- filingFileList  附件列表 -->
      <div class="area-header" style="margin-top: 20px;">
        <span class="area-header-title">{{ $t('附件列表') }}</span>
      </div>
      <el-table :data="form.filingFileList" border class="nowrapTable formTable">
        <el-table-column :label="$t('附件类型')" align="center" min-width="130">
          <template slot-scope="scope">
            {{ scope.row.directoryName }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('附件名称')" align="center" min-width="130">
          <template slot-scope="scope">
            <thumbnail :file-data="scope.row" :file-id="scope.row.fileId" />
            <el-input v-show="false" v-model="scope.row.fileId" />
          </template>
        </el-table-column>
        <!--filingNo 归档编号	          文本			自动生成，关联创建日期以YYYY-MMDD-001格式创建，唯一值 -->
        <el-table-column :label="$t('归档编号')" align="center" min-width="130">
          <template slot-scope="scope">
            <el-form-item :prop="'filingFileList.' + scope.$index + '.filingNo'">
              <el-input v-model="scope.row.filingNo" disabled :placeholder="$t('自动生成')" />
            </el-form-item>
          </template>
        </el-table-column>
        <!--paperFiling 是否需要纸质归档  单选 -->
        <el-table-column :label="$t('是否需要纸质归档')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <i style="color: red;">*</i>
            <span>{{ $t('是否需要纸质归档') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'filingFileList.' + scope.$index + '.paperFiling'" :rules="filingFileListRules.paperFiling">
              <el-radio-group v-model="scope.row.paperFiling" :disabled="archiveStatus" :placeholder="$t('是否需要纸质归档')" @change="paperFilingChange($event, scope.$index)">
                <el-radio label="是">{{ $t('是') }}</el-radio>
                <el-radio label="否">{{ $t('否') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-table-column>
        <!--archiveOrNot 当前是否归档	    单选			是、否、不适用；是否需要纸质归档为否时固定值为不适用；为是时不适用不可选；发起归档申请时不显示，仅归档人在归档时可编辑	-->
        <el-table-column v-if="form.actStatus === 'W' && (archiveStatus || form.archiveCompleted === '是')" :label="$t('当前是否归档')" align="center" min-width="150">
          <template slot="header" slot-scope="{}">
            <i style="color: red;">*</i>
            <span>{{ $t('当前是否归档') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'filingFileList.' + scope.$index + '.archiveOrNot'" :rules="filingFileListRules.archiveOrNot">
              <el-radio-group v-model="scope.row.archiveOrNot" :placeholder="$t('当前是否归档')" @change="archiveOrNotChange">
                <el-radio label="是">{{ $t('是') }}</el-radio>
                <el-radio label="否">{{ $t('否') }}</el-radio>
                <el-radio :disabled="scope.row.paperFiling === '是'" label="不适用">{{ $t('不适用') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-table-column>
        <!--filingDate 归档日期          日期     手动维护，发起归档申请时不显示，仅归档人在归档时可编辑 -->
        <el-table-column v-if="form.actStatus === 'W' && (archiveStatus || form.archiveCompleted === '是')" :label="$t('归档日期')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <i style="color: red;">*</i>
            <span>{{ $t('归档日期') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'filingFileList.' + scope.$index + '.filingDate'" :rules="filingFileListRules.filingDate">
              <DatePicker v-model="scope.row.filingDate" :placeholder="$t('归档日期')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['oa:filing:remove']" size="small" type="text" icon="el-icon-download" @click="downloadFile(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <div>
        <el-button v-if="archiveStatus && form.actStatus === 'W'" type="warning" @click="submitForm('type')">{{ $t('归档') }}</el-button>
      </div>
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:filing" />
    </div>
  </div>
</template>

<script>
import { saveOaFiling, getOaFiling } from '@/api/oa/filing/oaFiling'
import { getOaSeal, listOaSeal } from '@/api/oa/seal/oaSeal'
import { downLoadFileOpen } from '@/utils/zipdownload'

export default {
  data() {
    return {
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        archivingPersonnel: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        storagePlace: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        custodian: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        estimatedArchivingTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        sealId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      filingFileListRules: {
        paperFiling: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        filingDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      // 遮罩层
      loading: false,
      // 用印下拉
      sealListOption: [],
      // 操作按钮默认不展示
      buttonShow: true,
      sealTypeTwoOptions: [],
      archiveStatus: false
    }
  },
  watch: {
    'form.sealTypeOne': {
      handler(val) {
        if (val) {
          this.getDicts('seal_usine_type_' + val).then(response => {
            this.sealTypeTwoOptions = response.data
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDicts('seal_usine_type').then(response => {
      this.sealTypeOneOptions = response.data
    })
    // 获取用印列表
    listOaSeal({ actStatus: 'W' }).then(response => {
      this.sealListOption = response.rows
    })
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.archiveStatus = false
      this.initData(data)
    },
    initData(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getOaFiling(data.id).then(response => {
          this.form = response.data
          this.archiveOrNotChange()
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        sealId: undefined,
        archivingPersonnel: undefined,
        sealTypeOne: undefined,
        sealTypeTwo: undefined,
        storagePlace: undefined,
        custodian: this.$store.state.user.userId,
        applyTime: new Date(),
        estimatedArchivingTime: undefined,
        archiveCompleted: '否',
        remark: undefined,
        actId: undefined,
        actStatus: undefined,
        actTitle: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        filingFileList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            saveOaFiling(this.form).then(response => {
              if (response.code === 200) {
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  this.form.id = response.data.id
                  // 启动流程
                  this.startProcess(response.data.id)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // 业务表名
      processData.dataTable = 'oa_filing'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/filing/oaFilingForm.vue'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = 'oa_filing'
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 选择用印
    changeSeal(value) {
      console.log('选择用印')
      const seal = this.sealListOption.find(obj => obj.id === value)
      this.form.sealTypeOne = seal.usineTypeOne
      this.form.sealTypeTwo = seal.usineTypeTwo
      this.form.archivingPersonnel = seal.applyUserId
      // 获取该用印下的附件
      this.form.filingFileList = []
      getOaSeal(value).then(response => {
        if (response.code === 200) {
          if (response.data !== null && response.data.fileList !== null) {
            response.data.fileList.forEach(item => {
              this.form.filingFileList.push({ directoryName: item.directoryName, fileId: item.id, fileName: item.name })
            })
          }
        }
      })
    },
    downloadFile(row) {
      downLoadFileOpen('/file/fileBase/common/download?id=' + row.fileId)
    },
    // 是否需要纸质归档
    paperFilingChange(val, index) {
      if (val === '是') {
       this.form.filingFileList[index].archiveOrNot = ''
      } else {
        this.form.filingFileList[index].archiveOrNot = '不适用'
      }
    },
    //
    archiveOrNotChange() {
      debugger
      if (this.form.filingFileList !== undefined && this.form.filingFileList !== null) {
        var flag = true
        this.form.filingFileList.some(item => {
          if (item.archiveOrNot !== '是') {
            this.form.archiveCompleted = '否'
            flag = false
            return true
          }
        })
        if (flag) {
          this.form.archiveCompleted = '是'
        }
      }
    }

  }
}
</script>
